package de.smeurer.photoaccess;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private static final int PICTURE_MENU_DIALOG = 1333;
	protected static final int GALLERY_PIC_REQUEST = 1334;
	protected static final int CAMERA_PIC_REQUEST = 1335;
	private Bitmap bitmap;

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case PICTURE_MENU_DIALOG: {
		}
			final CharSequence[] items = { "From Gallery", "From Camera" };

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Where to get the image?");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					if (item == 0) {
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
						intent.setType("image/*");
						startActivityForResult(intent, GALLERY_PIC_REQUEST);
					} else if (item == 1) {
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
						startActivityForResult(intent, CAMERA_PIC_REQUEST);
					}
				}
			});
			dialog = builder.create();
		}
		return dialog;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Button b = (Button) findViewById(R.id.mainButtonChooseFile);
		
		b.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(PICTURE_MENU_DIALOG);
			}
		});

		final TextView tv = (TextView) findViewById(R.id.maintextview);

		tv.setText("Test!");

		WifiManager myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
		int ipAddress = myWifiInfo.getIpAddress();
		tv.setText("" + ipAddress);
		if (ipAddress != 0) {
			tv.setText("WiFi address is "
					+ android.text.format.Formatter.formatIpAddress(ipAddress));
		} else {
			tv.setText("No Wifi-Connection!");
		}

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					int port = 8080;
					ServerSocket server_socket;
					server_socket = new ServerSocket(port);

					// server infinite loop
					while (true) {
						Socket socket = server_socket.accept();
						// Construct handler to process the HTTP request
						// message.
						try {
							RequestHandler request = new RequestHandler(socket);
							// Create a new thread to process the request.
							Thread thread = new Thread(request);

							// Start the thread.
							thread.start();
						} catch (Exception e) {
							Log.e("", e.getMessage());
						}
					}
				} catch (IOException e) {
					Log.e("", e.getMessage());
				}
			}
		}).start();

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (bitmap != null) {
				bitmap.recycle();
				System.gc();
			}
			if (requestCode == CAMERA_PIC_REQUEST) {
				Log.d("ANDRO_CAMERA", "Picture taken!!!");
				bitmap = (Bitmap) data.getExtras().get("data");
			}
			if (requestCode == GALLERY_PIC_REQUEST) {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String filePath = cursor.getString(columnIndex);
				cursor.close();

				bitmap = BitmapFactory.decodeFile(filePath);

			}
		}
	}

	public void send_message_to_window(String s2) {
		TextView tv = (TextView) findViewById(R.id.maintextview);
		tv.setText(tv.getText().toString() + "\n" + s2);
	}

	class RequestHandler implements Runnable {
		final static String CRLF = "\r\n";

		Socket socket;

		OutputStream output;

		BufferedReader br;

		public RequestHandler(Socket socket) throws Exception {
			this.socket = socket;
			this.output = socket.getOutputStream();
			this.br = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		}

		public void run() {
			try {
				processRequest();
			} catch (Exception e) {
				Log.e("", e.getMessage());
			}
		}

		private void processRequest() throws Exception {
			while (true) {

				String headerLine = br.readLine();
				if (headerLine.equals(CRLF) || headerLine.equals(""))
					break;

				StringTokenizer s = new StringTokenizer(headerLine);
				String temp = s.nextToken();

				if (temp.equals("GET")) {

					if (bitmap != null) {

						try {
							ByteArrayOutputStream baos = new ByteArrayOutputStream();
							bitmap.compress(Bitmap.CompressFormat.JPEG, 70,
									baos);
							byte[] bdata = baos.toByteArray();

							// Send the status line.
							String statusLine = "HTTP/1.0 200 OK" + CRLF;
							output.write(statusLine.getBytes());

							// Send a blank line to indicate the end of the
							// header
							// lines.
							output.write(CRLF.getBytes());

							// Send data
							output.write(bdata);
						} catch (OutOfMemoryError e) {
							// Send not found.
							String statusLine = "HTTP/1.0 404" + CRLF;
							output.write(statusLine.getBytes());
						}
					}

				}
			}

			try {
				output.close();
				br.close();
				socket.close();
			} catch (Exception e) {
				Log.e("", e.getMessage());
			}
		}

	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.settings:
			startActivity(new Intent(this, Prefs.class));
			return true;
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}
}